package com.zjhcsoft.auth.service.impl;

import com.zjhcsoft.auth.common.utils.RandomUtils;
import com.zjhcsoft.auth.service.SmsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.zjhcsoft.auth.common.constant.RedisKeyConstant.SmsPrefix;

/**
 * @Author: wzya
 * @Date: 2021/3/23
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public String getSmsVrfcCode(String mobile) {

        String smsVrfcCd;
        //检查验证码是否过期
        Long expireTime = redisTemplate.opsForValue().getOperations().getExpire(SmsPrefix+"_"+mobile);
        if(expireTime<0){
            //生成6位短信验证码
            smsVrfcCd = RandomUtils.randomIntStr(6);
            redisTemplate.opsForValue().set(SmsPrefix+"_"+mobile, smsVrfcCd, 5, TimeUnit.MINUTES);
        }else {
            smsVrfcCd = redisTemplate.opsForValue().get(SmsPrefix+"_"+mobile);
        }
        //TODO 调用短信接口发送验证码

        return smsVrfcCd;
    }

    @Override
    public Boolean smsVrfcCodeValidate(String mobile, String smsVrfcCd) {
        //检验短信验证码
        String smsVrfCode = redisTemplate.opsForValue().get(SmsPrefix+"_"+mobile);
        return smsVrfcCd.equals(smsVrfCode)? true:false;
    }

}
